package com.fkjslee;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author fkjslee
 * @date 2018/4/30 at 10:26
 * Copyright (c) 2018 fkjslee. All rights reserved.
 */

@RestController
public class StationStateController {

    private static final Logger log = LoggerFactory.getLogger(StationStateController.class);

    private static Map<String, Station> stations = new HashMap<>();

    @RequestMapping(value = "sendStationState")
    public String sendStationState(HttpServletRequest request, String name, String taskNum) {
        String ip = Tool.getIpAddr(request);
        synchronized (stations) {
            if (stations.keySet().contains(ip + name)) {
                stations.remove(ip + name);
            }
            Station station = new Station(name, ip, taskNum);
            stations.put(ip + name, station);
        }
        return "";
    }

    @RequestMapping(value = "getStationState")
    public String getStationState() {
        JSONArray stationsArray = new JSONArray();
        for (String key : stations.keySet()) {
            Station value = stations.get(key);
            JSONObject oneStation = new JSONObject();
            oneStation.put("stationName", value.name);
            oneStation.put("stationIP", value.ip);
            oneStation.put("stationTaskNum", value.taskNum);
            stationsArray.add(oneStation);
        }
        return stationsArray.toString();
    }

    public static class Station{
        public String name;
        public String ip;
        public String taskNum;

        public Station(String name, String ip, String taskNum) {
            this.name = name;
            this.ip = ip;
            this.taskNum = taskNum;
        }
    }
}
